package com.iterator.service.wechat.lyh;

import com.iterator.bean.web.wy.storage.Storage;
import com.iterator.mapper.web.systemManager.StorageMapper;
import com.iterator.service.web.systemManager.StorageServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Service
public class WxStorageServiceImpl implements WxStorageService{

    @Autowired
    StorageMapper storageMapper;


    @Value("${file.winpath}")
    String winPath;

    @Value("${file.macpath}")
    String macPath;

    @Value("${file.prefixUrl}")
    String prefixUrl;

    @Override
    public Storage create(MultipartFile file, HttpServletRequest request) {
        String originalFilename = file.getOriginalFilename();
        //获取源文件内容的类型
        String contentType = file.getContentType();
        //获取文件大小
        int size = (int) file.getSize();
        //获取插入时间
        Date date = new Date();

        //获取文件名key
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //从原文件名中获取文件后缀，eg:1.png——>.png
        String s = originalFilename.substring(originalFilename.lastIndexOf("."));
        String key = uuid + s;

        //获取访问图片的url
        String url = prefixUrl + key;


        //文件上传逻辑：首先判断文件夹是否存在
        String path;
        File dir;
        try {
            path = winPath;
            dir = new File(path);
        } catch (Exception e){
            path = macPath;
            dir = new File(path);
        }
        dir.mkdirs();

        //上传文件
        try {
            file.transferTo(new File(path, key));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //更新数据库记录
        Storage storage = new Storage(null, key, originalFilename,
                contentType, size, url, date, date, false);
        int i = storageMapper.insertSelective(storage);
        if (i != 0) {
            return storage;
        }
        return null;
    }
}
